<?php
$deId = $_GET['pid'] > 0 ? $_GET['pid'] : $_POST['deId'];

if ($deId < 1 || $deId == '') {

    header('Location: part_location_list.php');
    exit;
}

error_reporting(E_ALL);

include_once('../controller/includes/db_access.php');

// we first include the upload class, as we will need it here to deal with the uploaded file

include_once('../controller/class.upload/class.upload.php');
$cli = (isset($argc) && $argc > 1);
if ($cli) {
    if (isset($argv[1]))
        $_GET['file'] = $argv[1];
    if (isset($argv[2]))
        $_GET['dir'] = $argv[2];
    if (isset($argv[3]))
        $_GET['pics'] = $argv[3];
}

// set variables
$dir_dest = (isset($_GET['dir']) ? $_GET['dir'] : 'test');
$dir_pics = (isset($_GET['pics']) ? $_GET['pics'] : $dir_dest);

//beveiliging tegen XSS aanval
function transforme_HTML($chaine, $longueur = null) {
// Aide à empêcher les attaques XSS
// Supression des espaces inutiles.
    $chaine = trim($chaine);
// Empêche des problèmes potentiels avec le codec Unicode.
    $chaine = utf8_decode($chaine);
// HTMLise les caractères spécifiques à HTML.
    $chaine = htmlentities($chaine, ENT_NOQUOTES);
    $chaine = str_replace("#", "&#35;", $chaine);
    $chaine = str_replace("%", "&#37;", $chaine);
    $longueur = intval($longueur);
    if ($longueur > 0) {
        
        $chaine = substr($chaine, 0, $longueur);
    
        
    }
    return $chaine;
}

if ((isset($_POST['action']) ? $_POST['action'] : (isset($_GET['action']) ? $_GET['action'] : '')) == 'multiple') {

   $set = transforme_HTML($_POST['naam']);
   $descr = transforme_HTML($_POST['descr']);
   $aktief = $_POST['aktief'];
   $deId = $_POST['deId'];
   $setprijs = $_POST['setprijs'];


     $query_sets = mysql_query("UPDATE  sets SET naam='$set', descr='$descr', setprijs=$setprijs, aktief='$aktief' WHERE set_id=". $deId );
        
     if ($query_sets) {
       // die($query_sets);
          $my_field = $_FILES['my_field']["name"];
       if($my_field) {
   
         // ---------- IMAGE UPLOAD ----------
        // we create an instance of the class, giving as argument the PHP object
        // corresponding to the file field from the form
        // All the uploads are accessible from the PHP object $_FILES
        $handle = new Upload($_FILES['my_field'], 'nl_NL');

        // then we check if the file has been uploaded properly
        // in its *temporary* location in the server (often, it is /tmp)
        if ($handle->uploaded) {

            // yes, the file is on the server
            // below are some example settings which can be used if the uploaded file is an image.
            
            $handle->image_resize = true;
            $handle->image_ratio = true;
            $handle->image_y = 100;
            $handle->image_x = 100;

            // now, we start the upload 'process'. That is, to copy the uploaded file
            // from its temporary location to the wanted location
            // It could be something like $handle->Process('/home/www/my_uploads/');

            $handle->Process('../my_uploads/sets/images');

            // we check if everything went OK
            if ($handle->processed) {
                // everything was fine !
                $query_foto = mysql_query("UPDATE  sets SET foto='". $handle->file_dst_name."' WHERE set_id=".$deId );
                
            } else {
                // one error occured

                echo '  Error_foto_kleine: ' . $handle->error . '';
            }
            if ($query_foto) {
                // yes, the file is on the server
                // below are some example settings which can be used if the uploaded file is an image.
                $handle->image_resize = true;
                $handle->image_ratio = true;
                $handle->image_y = 600;
                $handle->image_x = 600;

                // now, we start the upload 'process'. That is, to copy the uploaded file
                // from its temporary location to the wanted location
                // It could be something like $handle->Process('/home/www/my_uploads/');

                $handle->Process('../my_uploads/sets/images');

                // we check if everything went OK
                if ($handle->processed) {
                    // everything was fine !
                    //$query_foto_b = 
                    mysql_query("UPDATE  sets SET foto_b='" . $handle->file_dst_name . "' WHERE set_id=" . $deId);
                 } else {
                // one error occured

                echo '  Error_foto_big: ' . $handle->error . '';
            }

            // we delete the temporary files
          
            }
            
            } else {
            // if we're here, the upload file failed for some reasons
            // i.e. the server didn't receive the file

            echo "the server didn't receive the file:" . $handle->error . '';
        }
    
    }

    //if ($query_sets) {

        ///-----------PRODUCTEN UPDATE OF INSERT IN TABEL SET2PRODUCT-------------------------

        $select_allesamenstel = mysql_query("SELECT * FROM categorieen C, product P WHERE C.categorie_id = P.categorie_id  GROUP BY C.categorie_id");

        while ($q_allesamenstel = mysql_fetch_array($select_allesamenstel)) {
            
            $categorie_id = $q_allesamenstel['categorie_id'];
            
            $resultproduct = mysql_query('SELECT * FROM product WHERE categorie_id ='. $categorie_id );   
            while ($rowsproduct = mysql_fetch_object($resultproduct)) {
                
            $product_id = $rowsproduct->product_id;
           //$huurprijs = $rowsproduct->huurprijs;
            $aantal_product = $_POST['PROD_'.$product_id];
            $sql_set2product = "SELECT * FROM set2product WHERE product_id= $product_id AND set_id=" . $deId;
            $result_set2product = mysql_query($sql_set2product);
            //$set2product_array = mysql_fetch_array($result_set2product);
            $num_set2product = mysql_num_rows($result_set2product);
   
            $aktief = $_POST['aktief'];


            //kijken of des samenstel_id bestaat en 
               if($aantal_product && $num_set2product > 0){
           
                    // Insert a new user into the `user` table
                    $sql_UPDATE ="UPDATE set2product SET aantal=$aantal_product, product_id=$product_id, aktief='$aktief' WHERE set_id=". $deId; 
                    //die('UPDATE');
                $query_set2product = mysql_query($sql_UPDATE);
                
               }else if ($aantal_product > 0 && $num_set2product == 0) {
                   $sql_INSERT = "INSERT INTO set2product(aantal, product_id, set_id, prijs, aktief) VALUE($aantal_product, $product_id, $deId, $setprijs, '$aktief')";
                    //die($sql_INSERT);
                    $query_set2product = mysql_query($sql_INSERT);

                }else if ($aantal_product == 0 && $num_set2product > 0) {
                    
                    $sql_DELETE = "DELETE FROM set2product WHERE product_id =". $product_id ." AND set_id =". $deId ;
                    //die($sql_DELETE);
                    $query_set2product = mysql_query($sql_DELETE);
                    
                }else if ($aantal_product && $num_set2product == 0) {


                    }

        }
        
        }
         $my_doc = $_FILES["my_doc"]["name"];
         if($my_doc) {
        // we have three forms on the test page, so we redirect accordingly
        //if (isset($_FILES['my_doc'])) {
        // ---------- SIMPLE UPLOAD ----------
        // we create an instance of the class, giving as argument the PHP object
        // corresponding to the file field from the form
        // All the uploads are accessible from the PHP object $_FILES
        $doc_handle = new Upload($_FILES['my_doc']);

        // then we check if the file has been uploaded properly
        // in its *temporary* location in the server (often, it is /tmp)
        if ($doc_handle->uploaded) {

            // yes, the file is on the server
            // now, we start the upload 'process'. That is, to copy the uploaded file
            // from its temporary location to the wanted location
            // It could be something like $handle->Process('/home/www/my_uploads/');

            $doc_handle->Process('../my_uploads/sets/download');

            // we check if everything went OK
            if ($doc_handle->processed) {
                // everything was fine !
                $Q_setDownload = mysql_query("UPDATE  sets SET download='" . $doc_handle->file_dst_name . "' WHERE set_id=" . $deId);
            } else {
                // one error occured

                echo '  Error_doc1: ' . $doc_handle->error . '';
            }

            // we delete the temporary files
            $doc_handle->Clean();
        } else {
            // if we're here, the upload file failed for some reasons
            // i.e. the server didn't receive the file

            echo '  Error_doc2: ' . $doc_handle->error . '';
        }
         }

        //----------------------------TOEPASSING INSERT------------------------------ 

    $select_allesamenstel = mysql_query("SELECT toepassing_id FROM toepassingen ORDER BY sort ASC");
    
    while ($q_allesamenstel = mysql_fetch_array($select_allesamenstel)) {
        
    $toepassing_id = $q_allesamenstel["toepassing_id"];

      
    $sql_set2toepassing = "SELECT * FROM set2toepassing WHERE toepassing_id = $toepassing_id AND set_id=".$deId;
    $result_set2toepassing = mysql_query($sql_set2toepassing);
    //$set2toepassing_array = mysql_fetch_array($result_set2toepassingt);
    $num_set2toepassing = mysql_num_rows($result_set2toepassing);


        //kijken of des samenstel_id bestaat en 
    if (isset($_POST['toepassing_id'.$toepassing_id]) && $num_set2toepassing > 0) {

    header('Location: set_list.php');
    } else if (isset($_POST['toepassing_id'.$toepassing_id]) && $num_set2toepassing == 0) {

            // insert als samentel_id niet bestaat iedereen matvoering 

    $query_eindproduct = mysql_query("INSERT INTO set2toepassing(toepassing_id, set_id) VALUE(" . $toepassing_id . "," . $deId . ")");
    
            header('Location: set_list.php');
        } else if (!isset($_POST['toepassing_id'.$toepassing_id]) && $num_set2toepassing > 0) {

            echo $query_eindproduct = mysql_query("DELETE FROM set2toepassing WHERE toepassing_id = $toepassing_id AND set_id = $deId ");

            header('Location: set_list.php');
        }

        }// EIND foreach
        }
    
}
?>
<?php
if (isset($_GET['pid'])) {

    $id = $_GET['pid'];
    $q = new Query;
    $q
            ->select('*'
            )
            ->from('`sets`')
            ->where_equal_to(
                    array(
                        '`sets`.`set_id`' => $id,
                    )
    );

    $result = $q->run();

    if (!($result > 0)) {
        $Error = 'No category found.' . "\n";
    } else {
        $rows = mysql_fetch_object($result);
    }
}
?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <!--[if lt IE 9]>
        <script
        src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
        <![endif] -->
        <link rel="stylesheet" href="styles/style.css" type="text/css" />
        <!--[if lte IE 7]>
        <link rel="stylesheet" href="style_ie.css" />
        <![endif]-->
        <title>dbme!!!!</title>
        <script language="JavaScript" type="text/javascript">
            
            function CalculateTotal(frm) {
                var order_total = 0

                // Run through all the form fields
                for (var i=0; i < frm.elements.length; ++i) {
                        //alert(frm.elements.length)
                    // Get the current field
                    form_field = frm.elements[i]

                    // Get the field's name
                    form_name = form_field.name

                    // Is it a "product" field?
                    if (form_name.substring(0,4) == "PROD") {

                        // If so, extract the price from the name
                        item_id = parseFloat(form_name.substring(form_name.lastIndexOf("_") + 1))
                        //alert(item_id);
                        product_price_field='productprice_'+ item_id; 
                        
                        form_field_price = frm.elements[product_price_field]
                        form_name_price = form_field_price.name
                      //  alert(form_field_price.value);
                        // Get the quantity
                        item_quantity = parseInt(form_field.value)
                        item_price=parseInt(form_field_price.value)
                        // Update the order total
                        if (item_quantity >= 0) {
                            order_total += item_quantity * item_price
                        }
                    }
                }

                // Display the total rounded to two decimal places
                frm.TOTAL.value = round_decimals(order_total, 2)
            }

            function round_decimals(original_number, decimals) {
                var result1 = original_number * Math.pow(10, decimals)
                var result2 = Math.round(result1)
                var result3 = result2 / Math.pow(10, decimals)
                return pad_with_zeros(result3, decimals)
            }

            function pad_with_zeros(rounded_value, decimal_places) {

                // Convert the number to a string
                var value_string = rounded_value.toString()
    
                // Locate the decimal point
                var decimal_location = value_string.indexOf(".")

                // Is there a decimal point?
                if (decimal_location == -1) {
        
                    // If no, then all decimal places will be padded with 0s
                    decimal_part_length = 0
        
                    // If decimal_places is greater than zero, tack on a decimal point
                    value_string += decimal_places > 0 ? "." : ""
                }
                else {

                    // If yes, then only the extra decimal places will be padded with 0s
                    decimal_part_length = value_string.length - decimal_location - 1
                }
    
                // Calculate the number of decimal places that need to be padded with 0s
                var pad_total = decimal_places - decimal_part_length
    
                if (pad_total > 0) {
        
                    // Pad the string with 0s
                    for (var counter = 1; counter <= pad_total; counter++) 
                        value_string += "0"
                }
                return value_string
            }

        </script>

    </head>
    <body onload="CalculateTotal(document.forms.form1)">
        <div id="bloc_page">
            <header>
                <a href="#"><img src="../images/dBmelogo.png" alt="referentie" alt="dbme!" /></a>
            </header>  
            <nav>
<?php include_once('header.php'); ?>
            </nav>
            <section>
                <aside>
                    <!--right side baar -->  
                </aside>

                <article>  
                    <table border="0" width="900" cellspacing="5" cellpadding="5">
                        <form name="form1" method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">
                            <input type="hidden" name="action" value="multiple" />  
                            <input type="hidden" name="deId" value="<?php echo $deId; ?>" /> 

                            <tbody>
                                <tr>
                                    <td width="10%">Naam</td>
                                    <td><input type="text" name="naam" value="<?php echo $rows->naam; ?>" size="20" /></td>
                                    <td></td>
                                </tr>
                                <tr>
                                    <td>Beschrijving</td>
                                    <td><textarea name="descr" rows="4" cols="20">
<?php echo $rows->descr; ?>
                                        </textarea></td>
                                    <td></td>
                                </tr>
                                <tr>
                                    <td>Foto</td>
                                 
                                    <td><p><input type="file" name="my_field" value="" size="20" /></p>
                                        <p><img src="../my_uploads/sets/images/<?php echo $rows->foto_b; ?>" style=" width:100px; border:1px solid #ffffff; border-radius: 100px;"/> &nbsp; <img src="../my_uploads/sets/images/<?php echo $rows->foto; ?>"  style="width:50px; border:1px solid #ffffff; border-radius: 50px;" /></p> </td>
                                    <td></td>
                                </tr>
                                <tr>
                                    <td colspan="3">________________________________Samenstellen____________________________________</td>

                                </tr>
                                <tr>
                                    <td>aantal</td>
                                    <td>products</td>
                                    <td></td>
                                </tr>




<?php
$resultProductCategorie = mysql_query('SELECT * FROM categorieen C, product P WHERE C.categorie_id = P.categorie_id  GROUP BY C.categorie_id');

while ($rowsproductCategorie = mysql_fetch_object($resultProductCategorie)) {
    ?> 
                                    <tr>
                                        <td colspan="2" ><?php echo $rowsproductCategorie->categorie; ?></td>

                                        <td></td>
                                    </tr>
                                    <?php
                                    $resultproduct = mysql_query('SELECT * FROM product WHERE categorie_id =' . $rowsproductCategorie->categorie_id);

                                    $count = mysql_num_rows($resultproduct);
                                    while ($rowsproduct = mysql_fetch_object($resultproduct)) {
                                        $product_id = $rowsproduct->product_id;
                                         $sql_set2product = "SELECT * FROM set2product WHERE product_id = $product_id AND set_id=" . $deId;
                                         $result_set2product = mysql_query($sql_set2product);
                                         $rows_set2product = mysql_fetch_object($result_set2product);
                                        ?> 


                                        <tr>
                                            <td colspan="2">


                                                <input type="hidden" name="product_id" value="<?php echo $rowsproduct->product_id; ?>" />
                                                <input type="hidden" name="productprice_<?php echo $rowsproduct->product_id; ?>" value="<?php echo $rowsproduct->huurprijs; ?>" />
                                                <select id="testSelect" NAME="PROD_<?php echo $rowsproduct->product_id; ?>" onChange="CalculateTotal(this.form,<?php echo $rowsproduct->product_id; ?>)">
                                                    <option>--aantal--</option
                                        <?php for ($i = 0; $i <= $rowsproduct->aantal; $i++) { ?>

                                                        <option value="<?php echo $i ?>" <?php echo $i == $rows_set2product->aantal ? 'selected' : ''; ?> > <?php echo $i ?></option>

                                        <?php } ?>


                                                </select> 

                                            <?php echo $rowsproduct->naam; ?> (<?php echo $rowsproduct->aantal; ?>)</td>

                                            <td>

                                                Huurprijs &euro;<?php echo $rowsproduct->huurprijs; ?>

                                            </td>
                                        </tr>  

                                                <?php }
                                            } ?>


                                <tr>
                                    <td><p>berekende prijs</p>
                                        <p>set prijs</p> </td>

                                    <td>
                                        <p><INPUT TYPE=TEXT readonly="readonly" NAME=TOTAL SIZE=10 onFocus="this.form.elements[0].focus()" /></p>
                                        <p><INPUT TYPE="text" name="setprijs" value="<?php echo $rows->setprijs; ?>" size="10"/></p>
                                    </td>
                                    <td></td>
                                </tr>
                                <tr>
                                    <td>download</td>
                                    <td>
                                        <p><a href="../my_uploads/sets/download/<?php echo $rows->download; ?>"><?php echo $rows->download; ?></a></p><p><input type = "file" name="my_doc" value="" size="10" />--(PDF, DOC)</p></td>
                                    <td></td>
                                </tr>
                                <tr>
                                    <td>Aktief</td>
                                    <td>
                                        <input name="aktief" type="radio"  id="aktief" value="Y" <?php if ($rows->aktief == 'Y')
                                                echo ' checked'; ?> /> Ja 
                                        <input name="aktief" type="radio"  id="aktief" value="N" <?php if ($rows->aktief != 'Y')
                                                echo ' checked'; ?> /> Nee</td>
                                    <td></td>
                                </tr>
                                <tr>
                                    <td colspan="3">___________________________________Toepassingen_________________________________</td>
                                </tr>

<?php


    
$q = new Query;
$q->select('*')
        ->from('`toepassingen`')
        ->order_by(array('`toepassingen`.`sort` ASC',))
        ->run();

$result = $q->run();
while ($rows_toepassing = mysql_fetch_object($result)) {
    
    $SQL_checked = "SELECT toepassing_id FROM set2toepassing WHERE set_id =".$id." AND toepassing_id=".$rows_toepassing->toepassing_id;
    $result_checked = mysql_query($SQL_checked);
   $rows_checked = mysql_fetch_object($result_checked);
    $checked = $rows_toepassing->toepassing_id == $rows_checked->toepassing_id ? 'checked' : '';

   

    ?>

                                    <tr><td colspan="3"> <input type="checkbox" name="toepassing_id<?php echo $rows_toepassing->toepassing_id ?>" value="<?php echo $rows_toepassing->toepassing_id ?>" <?php echo $checked; ?> />
                                    <?php echo $rows_toepassing->sort ?></td></tr>

                                <?php   }?>




                                <tr>
                                    <td></td>
                                    <td><input type = "submit" name="save" value="save" size="10" /></td>
                                    <td></td>
                                </tr>

                            </tbody> 
                        </form>
                    </table>
                </article>

                <aside>
                    <!--right side baar -->


                </aside>
            </section>

            <footer>  
                <p>Lorem ipsum dolor sit amet...</p>
                <p>Vivamus sed libero nec mauris pulvinar facilisis ut non sem...</p>
                <p>Phasellus ligula massa, congue ac vulputate non, dignissim at augue...</p>
            </footer>
        </div>

    </body>
</html>

